//
//  STGroupViewController.swift
//  frameAndGroupAnimationSwift
//
//  Created by Stan on 2017-02-15.
//  Copyright © 2017 stan. All rights reserved.
//

import UIKit

class STGroupViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()


//设置layer的position
        orangeLayer.position = view.center
        
//将layer添加到view的layer上。就类似自定义的view要添加到controller的view上才能显示一样
        view.layer.addSublayer(orangeLayer)

//为layer添加动画
        orangeLayer.add(createGroupAnimation(), forKey: nil)
        
        
    }
    
    
//    MARK: - 懒加载orangeLayer
    lazy var orangeLayer: CALayer = {
        let orangeLayer = CALayer()
        orangeLayer.bounds = CGRect(x: 0, y: 0, width: 150, height: 150)
        orangeLayer.backgroundColor = UIColor.orange.cgColor
        
        return orangeLayer
    }()

}

extension STGroupViewController{

//    MARK: - 创建动画
    fileprivate func createGroupAnimation() -> (CAAnimationGroup){
        
//        实例化一个组动画对象
       let groupAnimation = CAAnimationGroup()
        
//        创建旋转的动画
        let basicRotation = CABasicAnimation(keyPath: "transform.rotation.z")
        basicRotation.toValue = Float.pi * 2
        
        
//        创建缩放的动画
        let basicScale = CABasicAnimation(keyPath: "transform.scale")
        basicScale.toValue = 0.2
        
        
//        创建按照路径移动的动画
        let keyFrameAnimation = CAKeyframeAnimation(keyPath: "position")
        let endAngle = Float.pi * 2
        let arcPath = UIBezierPath(arcCenter: view.center, radius: 150, startAngle: 0, endAngle: CGFloat(endAngle), clockwise: true)
        keyFrameAnimation.path = arcPath.cgPath
        keyFrameAnimation.calculationMode = kCAAnimationPaced
        keyFrameAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
        
        
        
        let rotation = basicRotation as CAAnimation
        let scale = basicScale as CAAnimation
        let keyFrame = keyFrameAnimation as CAAnimation
        
//        将旋转、缩放、移动的动画添加到组动画中
        groupAnimation.animations = [rotation,scale,keyFrame]
//        组动画重复次数
        groupAnimation.repeatCount = MAXFLOAT
//        组动画时长
        groupAnimation.duration = 2
        
        return groupAnimation
        
    }


}
